/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-09-12 17:10:37
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-10-23 09:23:33
 * @FilePath: /utools_web/src/components/DragModal/Tagtemplate/index.jsx
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import { getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import { Spin, Tabs, Tag, theme } from 'antd';
import { useState } from 'react';

const { CheckableTag } = Tag;

function SelectTags({ id, value, onChange }) {
  const { token } = theme.useToken();

  const { data, loading } = useRequest(
    async () => {
      let res = await getFetch({ url: '/orgTagTemplate', params: { orgTagTypeId: id } });
      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
      refreshDeps: [id],
    },
  );

  const allchecklist = data ?? [];

  const handleChange = (tag, checked) => {
    const nextValue = checked
      ? [
          ...value,
          {
            id: tag?.id,
            name: tag.name,
            color: tag.color,
          },
        ]
      : value.filter((t) => t?.id !== tag?.id);
    console.log('You are interested in: ', nextValue);
    onChange(nextValue);
  };

  return (
    <Spin spinning={loading}>
      {allchecklist.map((tag) => {
        const checked = value.some((it) => it?.id === tag?.id);
        return (
          <CheckableTag
            key={tag?.id}
            checked={checked}
            onChange={(checked) => handleChange(tag, checked)}
            style={{
              marginBottom: '10px',
              backgroundColor: checked ? token.colorPrimary : null,
              color: checked ? '#fff' : tag?.color,
            }}
          >
            <span>{tag?.name}</span>
          </CheckableTag>
        );
      })}
    </Spin>
  );
}

function Tagtemplate({ value, onChange }) {
  const [activeKey, setActiveKey] = useState();
  const { data } = useRequest(
    async () => {
      let res = await getFetch({ url: '/orgTagType', params: {} });
      setActiveKey(res?.data?.dataList?.[0]?.id);
      return res?.data?.dataList?.map((item) => ({
        key: item?.id,
        label: item?.name,
      }));
    },
    {
      debounceWait: 400,
    },
  );

  return (
    <div style={{ width: '100%' }}>
      <Tabs items={data ?? []} activeKey={activeKey} onChange={setActiveKey} size="small" />
      <div>
        <SelectTags id={activeKey} value={value} onChange={onChange} />
      </div>
    </div>
  );
}

export default Tagtemplate;
